package com.wanmait.gohome.filter;

import com.wanmait.gohome.mapper.UserinfoMapper;
import com.wanmait.gohome.pojo.Userinfo;
import com.wanmait.gohome.service.UserinfoService;
import com.wanmait.gohome.util.CookieUtil;
import com.wanmait.gohome.util.Md5;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@WebFilter("/*")
public class UserinfoAutoLoginFilter implements Filter {

    private UserinfoService userinfoService;

    public void destroy(){
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpSession session = request.getSession();
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        //如果已经登录，放行
        if(userinfo!=null)
        {
            chain.doFilter(req,resp);
            return;
        }

        //读取cookie，实现自动登录
        String phone = CookieUtil.getCookie("phone",request);
        String userpass = CookieUtil.getCookie("password",request);


        userinfo = userinfoService.findByPhone(phone);

        if(userinfo!=null && userinfo.getUserpass()!=null)
        {
            String userinfoPassword = Md5.getSuperMD5(userinfo.getUserpass());

            if(userinfoPassword.equals(userpass))
            {
                //登录成功
                session.setAttribute("userinfo",userinfo);
                Userinfo userinfo2 = new Userinfo();
                userinfo2.setId(userinfo.getId());
                userinfo2.setIp(request.getRemoteAddr());
                userinfo2.setLoginCount(userinfo.getLoginCount()+1);
                userinfo2.setLastLoginTime(new Date());
                userinfoService.updateById(userinfo2);
                //重写cookie
                CookieUtil.addCookie("phone",userinfo.getPhone(),"/",60*60*24*30,response);

                CookieUtil.addCookie("password", userinfo.getUserpass(),"/",60*60*24*30,response);

            }
        }

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        userinfoService = applicationContext.getBean(UserinfoService.class);

    }

}
